package view;

import com.alibaba.fastjson.JSON;
import model.ViewForReport;
import pond.common.Convert;
import pond.common.FILE;
import pond.common.S;
import pond.common.STRING;
import pond.web.Render;
import pond.web.Router;
import service.DataBaseService;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by sky_wang on 2017/7/19.
 */
public class Report extends Router {
    private DataBaseService dataBaseService;
    public Report (DataBaseService dataBaseService){
        this.dataBaseService = dataBaseService;
    }
    {
        get("/list", (req, resp) -> {
            List<ViewForReport> ret = dataBaseService.getDB().get(t -> t.query(ViewForReport.class, "select * from view_for_report;"));
            resp.render(Render.json(ret));
        });

        get("/:id", (req, resp) -> {
            String id = req.paramNonBlank("id", "id不能为空");
            List<ViewForReport> ret = dataBaseService.getDB().get(t -> t.query(ViewForReport.class, "select * from view_for_report where vid = '" + id + "';"));
            if (ret.size() == 0) {
                resp.send(403, "report not existed ");
            }
            ViewForReport vfr =ret.get(0);
            String data ="";
            if (new File(vfr.get("report_data").toString()).exists())
            {
                try {
                    for(String line : Files.readAllLines(Paths.get(vfr.get("report_data").toString()))){
                        data +=line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(data);
            vfr.set("report_data",data);
            resp.render(Render.json(vfr));
        });

        post("/new", (req, resp) -> {
            String data = req.param("data");
            if (STRING.isBlank(data)) {
                resp.send("null parm");
            }
            Map<String, Object> map = (Map<String, Object>) JSON.parse(data);
            ViewForReport vfr = new ViewForReport();
            vfr.setId(S.uuid.vid());
            vfr.set("report_name", map.get("report_name"));

            File file = new File(dataBaseService.getDataDir(), map.get("view_for_grid_id") + "_" + Convert.toString(new Date(), "YYYYMMDDHHMMSS") + ".txt");
            vfr.set("report_data", file.getAbsolutePath());
            try {
                FILE.inputStreamToFile(new ByteArrayInputStream(map.get("report_data").toString().getBytes()), file);
            } catch (IOException e) {
                e.printStackTrace();
            }

            vfr.set("view_for_grid_id", map.get("view_for_grid_id"));

            dataBaseService.getDB().post(t -> {
                t.recordInsert(vfr);
            });
            resp.send(200, "ok");
        });
    }
}
